<?php

class Backend_AclController extends Backend_Libraries_Controller_Action 
{

    public function indexAction() {
        $message = $this->_request->getParam('message', '');
        $error = $this->_request->getParam('error', '');
        
        //roles
        $roles = $this->_em->getRepository('Entities\Acl_Role')->findAll();
        
        //form add role
        $frmAddRole = new Backend_Form_Role();

        //resources
        $resources = $this->_em->getRepository('Entities\Acl_Resource')->findAll();
        $db_structure = $this->getListControllerAcitons();
        
        $this->view->roles = $roles;
        $this->view->resources = $resources;
        $this->view->resource_missing = $this->getMissing($resources, $db_structure);
        $this->view->frmAddRole = $frmAddRole;
        $this->view->message = $message;
        $this->view->error = $error;
        
    }
    
    public function addroleAction() 
    {
        $frmAddRole = new Backend_Form_Role();

        if($this->_request->isPost())  
        {
            if($frmAddRole->isValid($this->_request->getPost()))
            {
                $role = new \Entities\Acl_Role();
                $role->setName($this->_request->getParam('name'));

                $this->_em->persist($role);
                $this->_em->flush();

                $this->_redirect('backend/acl/index/message/'. urlencode('Insert Role successful') );
            }
//            $this->_redirect('backend/acl/index/error/'. urlencode('Insert Role fail') );
        }
        $this->_redirect('backend/acl');
    }
    
    public function addresourceAction()
    {
        if ($this->_request->isXmlHttpRequest()) 
        {
            if($this->_request->isPost()) 
            {
                $resource = new Entities\Acl_Resource();
                $resource->setModule($this->_request->getParam('module_name'));
                $resource->setController($this->_request->getParam('controller_name'));
                $resource->setAction($this->_request->getParam('action_name'));
                
                $this->_em->persist($resource);
                $this->_em->flush();
                
                $this->_helper->json(array(
                    'message'=>'success',
                    'module'=>$resource->getModule(),
                    'controller'=>$resource->getController(),
                    'action'=>$resource->getAction()
                    ));

                exit;
            }
        }
        $this->_helper->json(array(
            'message'=>'fail', 
            'module'=>$resource->getModule(),
            'controller'=>$resource->getController(),
            'action'=>$resource->getAction()
            ));
        exit;
    }
    
    public function removeresourceAction()
    {
        if ($this->_request->isXmlHttpRequest()) 
        {
            if($this->_request->isPost()) 
            {
                $resource = $this->_em->getRepository('Entities\Acl_Resource')->find($this->_request->getParam('resource_id'));

                if ($resource) {
                    try {
                        $this->_em->remove($resource);
                        $this->_em->flush();
                        $this->_helper->json(array(
                            'message'=>'success',
                            ));
                    }
                    catch (Exception $e) {
                        $this->_helper->json(array(
                            'message'=>'You can not delete this item. It\'s may be have some privilege on it.', 
                            ));
                    }
                }
            }
        }
        $this->_helper->json(array(
            'message'=>'fail', 
            ));
        exit;
    }


    private function getMissing($resources, $all_resources)
    {
        $arr = array();
        foreach ($all_resources as $module_name => $module)
        {
            foreach ($module as $controller_name => $controller) {
                foreach ($controller as $action) {
                    if (!$this->isExistInResources($resources, $module_name, $controller_name, $action)) {
                        $arr[] = array(
                            'module' => $module_name,
                            'controller' => $controller_name,
                            'action' => $action
                            );
                    }
                }
            }
        }
        return $arr;
    }
    
    private function isExistInResources($resources, $module, $controller, $action)
    {
        foreach ($resources as $resource)
        {
            if ($resource->getModule()==$module && $resource->getController()==$controller && $resource->getAction()==$action) {
                return true;
            }
        }

        return false;
    }
    
    private function getListControllerAcitons()
    {
        $module_dir = substr(str_replace("\\","/",$this->getFrontController()->getModuleDirectory()),0,strrpos(str_replace("\\","/",$this->getFrontController()->getModuleDirectory()),'/'));
        $temp = array_diff( scandir( $module_dir), Array( ".", "..", ".svn"));
        $modules = array();
        $controller_directorys = array();
        foreach ($temp as $module) {
            if (is_dir($module_dir . "/" . $module)) {
                array_push($modules,$module);
                array_push($controller_directorys, str_replace("\\","/",$this->getFrontController()->getControllerDirectory($module)));
            }
        }

        foreach ($controller_directorys as $dir) {
            foreach (scandir($dir) as $dirstructure) {
                if (is_file($dir  . "/" . $dirstructure)) {
                    if (strstr($dirstructure,"Controller.php") != false) {
                        include_once($dir . "/" . $dirstructure);
                    }
                }

            }
        }

        $default_module = $this->getFrontController()->getDefaultModule();

        $db_structure = array();

        foreach(get_declared_classes() as $c){
            if(is_subclass_of($c, 'Zend_Controller_Action')){
                $functions = array();
                foreach (get_class_methods($c) as $f) {
                    if (strstr($f,"Action") != false) {
                            array_push($functions,substr($f,0,strpos($f,"Action")));
                    }
                }
                $c = strtolower(substr($c,0,strpos($c,"Controller")));

                if (strstr($c,"_") != false) {
                    $db_structure[substr($c,0,strpos($c,"_"))][substr($c,strpos($c,"_") + 1)] = $functions;
                }else{
                    $db_structure[$default_module][$c] = $functions;
                }
            }
        }           

        return $db_structure;
    }

}